/*
* @Author: Administrator
* @Date:   2017-10-24 09:16:40
* @Last Modified by:   Administrator
* @Last Modified time: 2018-02-05 15:15:10
*/
import axios from 'axios';
// 兼容浏览器
import * as ES6Promise from 'es6-promise';

const host = process.env.API_BASE || ''
const qs = require('qs')

try {
  ES6Promise.polyfill();
} catch (e) {
  console.log(e); // eslint-disabel-line
}
// 将参数对象转换成字符串
function obj2params(obj) {
  let result = '';
  let item;
  for (item in obj) { //eslint-disable-line
    result += `&${item}=${encodeURIComponent(obj[item])}`;
  }
  if (result) {
    result = result.slice(1);
  }
  return result;
}

const { CancelToken } = axios;
const source = CancelToken.source();
// get方法
if (!Object.assign) {
  (function () {
    Object.assign = function (target) {
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert undefined or null to object');
      }
      const output = Object(target);
      for (let index = 1; index < arguments.length; index++) {
        const source = arguments[index]; //eslint-disable-line
        if (source !== undefined && source !== null) {
          for (const nextKey in source) { //eslint-disable-line
            if (source.hasOwnProperty(nextKey)) { //eslint-disable-line
              output[nextKey] = source[nextKey]; //eslint-disable-line
            }
          }
        }
      }
      return output;
    };
  }());
}
const _fetch = (axios => (url, options) => { //eslint-disable-line
  return axios(url, Object.assign(
    {
      cancelToken: source.token,
    },
    options,
  ))
})(axios);
export function get(baseUrl, params, headersParam = {}) {
  const url = `${host}${baseUrl}?${obj2params(params)}`;
  const headers = Object.assign({}, {
    Accept: 'application/json, text/plain, */*',
  }, headersParam)
  const result = _fetch(url, {
    credentials: 'include',
    headers,
  });

  return result;
}
// 发送 post 请求
export function post(url, paramsObj, headersParam = {}) {
  const result = _fetch(
    url,
    {
      method: 'POST',
      headers: headersParam,
      data: qs.stringify(paramsObj),
    },
  )
  return result;
}
export function dle(url, paramsObj, headersParam = {}) {
  const headers = Object.assign({}, {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': 'application/x-www-form-urlencoded',
  }, headersParam)
  const result = _fetch(url, {
    method: 'DELETE',
    headers,
    data: obj2params(paramsObj),
  });
  return result;
}
export function postFile(url, formdata, headersParam = {}) {
  const headers = headersParam;
  const result = _fetch(url, {
    method: 'POST',
    headers,
    data: formdata,
  });
  return result;
}
export function cancelRequest() {
  // source.cancel('Operation canceled by the user.');
}
